<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>计算数组的和</title>
	</head>

	<body>
		<script>
			function computed(array = [], ...arg) {
				if (Array.isArray(array) && array.length > 0) {
					const item = array[0];
					const type = Object.prototype.toString.call(item);
					if (type === '[object Object]') {
						if (!arg.length) {
							throw 'If you want to sum some value in the object, pass a key value';
						}
						const key = arg[0];
						array = array.map((item) => item[key]);
					}
					array = array.filter((item) => Boolean(item));
					return array.reduce((pre, crt) => (pre += crt * 1), 0);
				}
				if (arg.length > 0) {
					const result = arg.reduce(
						(pre, crt) => (pre += crt * 1),
						0
					);
					return result + array * 1;
				} else {
					return array;
				}
			}
			const result = computed();
			console.log('result', result);
		</script>
	</body>
</html>
